/*
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 Created by Youssef Francis and Pepijn Oomen.
*/

#include <sys/types.h>
#include <sys/stat.h>

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <getopt.h>

#include "GetPID.h"

static const char *ARD_AGENT_EXEC = "/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent";

static int nosuid = 0;
static int noscript = 0;
static int killard = 0;

int main(int argc, char *argv[]) {
	// parse options from command line
	int c;
	while (1) {
		static struct option long_options[] = {
			{"nosuid", no_argument, &nosuid, 1},
			{"noscript", no_argument, &noscript, 1},
			{"killard", no_argument, &killard, 1},
			{0, 0, 0, 0}
		};
		c = getopt_long(argc, argv, "", long_options, NULL);
		if (c == -1) {
			break;
		}
	}

	if (nosuid || noscript || killard) {
		// we want superuser privs
		setuid(0);
		setgid(0);

		// remove user suid bit from executable
		if (nosuid) {
			struct stat stat;
			lstat(ARD_AGENT_EXEC, &stat);
			if (stat.st_mode & S_ISUID) {
				chmod(ARD_AGENT_EXEC, stat.st_mode & ~S_ISUID);
			}
			killard = 1;
		}

		// prevent scripting of ARD agent
		if (noscript) {
			system("/usr/bin/defaults write /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Info NSAppleScriptEnabled -boolean YES");
			chmod("/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Info.plist", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
			killard = 1;
		}

		// remove agent process to make changes take effect
		if (killard) {
			const int kPIDArrayLength = 5;
			
			pid_t pid[kPIDArrayLength];
			unsigned int matches;
			int err;
			
			err = GetAllPIDsForProcessName("ARDAgent", pid, kPIDArrayLength, &matches, NULL);
			if (err == 0) {
				for (int i = 0; i < matches; i++) {
					kill(pid[i], SIGTERM);
				}
			}
		}
	}
}
